﻿using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace MathService.Temp
{
    public static class GoogleTranslateAPI
    {
        public static string GetTranslateFull(string Word)
        {
            const string address = "http://translate.google.com.ua";
            const string subaddress = "translate_a";
            var request = WebRequest.Create(
                string.Format(@"{0}/{1}/{2}?client={2}&text={3}&hl={4}&sl={5}&tl={4}" +
                              @"&ie={6}&oe={6}&multires={7}&prev={8}&ssel={9}&tsel={10}&sc={11}",
                    "t",
                    address, subaddress,
                    Word,
                    "ru", "en",
                    "UTF-8", 1, "btn", 0, 0, 1));
            var response = (HttpWebResponse)request.GetResponse();
            //string data = null;
            using(var DataStream = response.GetResponseStream())
            {
                if(DataStream == null) return null;
                using(var DataStreamReader = new StreamReader(DataStream))
                    return DataStreamReader.ReadToEnd();
            }
        }

        public static string Translate(string Word)
        {
            var FullTRanslate = GetTranslateFull(Word);
            if(string.IsNullOrEmpty(FullTRanslate)) return FullTRanslate;

            const string regex = "(?<=\\[\\[\\[\\\")\\w*(?=\\\")";
            var RegExMatch = new Regex(regex).Match(FullTRanslate);
            return !RegExMatch.Success ? null : RegExMatch.Value;
        }
    }
}
